package safrain.nodelet.pool;

import java.util.ArrayList;
import java.util.List;

import safrain.nodelet.pool.reseter.IReseter;
import safrain.nodelet.structure.FieldInfo;
import safrain.nodelet.structure.Structure;

public class ObjectPool {
	private final List<Object> objects = new ArrayList<Object>();
	private final List<IReseter> reseterList = new ArrayList<IReseter>();
	private Class<?> type;
	private int poolSize;

	public ObjectPool(Structure structure, int poolSize) {
		this.type = structure.type;
		this.poolSize = poolSize;
		List<FieldInfo> fieldInfoList = structure
				.getFieldInfoList(Pool.class);
		int size = fieldInfoList.size();
		for (int i = 0; i < size; i++) {
			FieldInfo fieldInfo = fieldInfoList.get(i);
			Pool poolFieldAnnotation = (Pool) fieldInfo.annotation;
			Class<? extends IReseter> reseterClass = poolFieldAnnotation
					.reseterClass();
			try {
				IReseter reseter = reseterClass.newInstance();
				reseter.init(fieldInfo);
				reseterList.add(reseter);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public Object get() {
		if (!objects.isEmpty()) {
			Object object = objects.remove(objects.size() - 1);
			return object;
		}
		try {
			return type.newInstance();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public void recycle(Object object) {
		if (objects.size() < poolSize) {
			int size = reseterList.size();
			for (int i = 0; i < size; i++) {
				reseterList.get(i).reset(object);
			}
			objects.add(object);
		}
	}
}